package org.jeecg.common.json;

import com.alibaba.fastjson.serializer.NameFilter;

/**
 * 大写蛇行命名json序列化器
 *
 * @author zhanglei01
 * @date 2022/03/09
 */
public class SnakeCaseJsonSerializer implements NameFilter {

    private static final SnakeCaseJsonSerializer instance = new SnakeCaseJsonSerializer();

    private SnakeCaseJsonSerializer() {
    }

    public static SnakeCaseJsonSerializer getInstance() {
        return instance;
    }

    @Override
    public String process(Object object, String name, Object value) {
        if (name == null || name.length() == 0) {
            return name;
        }
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < name.length(); ++i) {
            char ch = name.charAt(i);
            if (ch >= 'A' && ch <= 'Z') {
                char ch_ucase = (char) (ch + 32);
                if (i > 0) {
                    buf.append('_');
                }
                buf.append(ch_ucase);
            } else {
                buf.append(ch);
            }
        }
        name = buf.toString().toUpperCase();
        return name;
    }
}